/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(inorder.size() == 0 || postorder.size() == 0){
            return NULL;
        }
        return Tree(0, inorder.size()-1, 0, postorder.size()-1, inorder, postorder);
    }
    TreeNode* Tree(int in_left, int in_right, int post_left, int post_right,vector<int>& in, vector<int>& post){
        if(in_left > in_right){
            return NULL;
        }
        TreeNode* root = new TreeNode(post[post_right]);
        int i = in_left;
        for(;i<in_right;i++){
            if(in[i]==post[post_right]){
                break;
            }
        }
        int left = i - in_left;
        root->left=Tree(in_left, i-1, post_left,  post_left+left-1,in,post);
        root->right=Tree(i + 1, in_right, post_left + left, post_right - 1, in, post);
        return root;
    }
};
